package cn.fafu.fafu_record.controller;


import cn.fafu.fafu_record.annotation.PassToken;
import cn.fafu.fafu_record.annotation.VerifyToken;
import cn.fafu.fafu_record.entity.Image;
import cn.fafu.fafu_record.result.Result;
import cn.fafu.fafu_record.result.ResultEnum;
import cn.fafu.fafu_record.service.ImageService;
import cn.fafu.fafu_record.utils.FileUploadUtil;
import cn.fafu.fafu_record.utils.ResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadController {

    @Autowired
    ImageService imageService;


    @VerifyToken
    @PassToken
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        System.out.println(file.getOriginalFilename());
        if (file.isEmpty()) {
            return ResultUtil.error(ResultEnum.NULL_FILE_ERROR.getCode(), ResultEnum.NULL_FILE_ERROR.getMsg());
        }
        String path = FileUploadUtil.uploadFile(file);
        if (!StringUtils.isEmpty(path)) {
            //将图片url存进数据表
            Image image = new Image();
            image.setLocalurl(path);
            imageService.addImage(image);
            Map<String, String> data = new HashMap<>();
            data.put("path", path);
            return ResultUtil.success(data);

        } else {
            return ResultUtil.error(ResultEnum.UPLOAD_FILE_ERROR.getCode(), ResultEnum.UPLOAD_FILE_ERROR.getMsg());
        }
    }

}
